﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Data.SqlServerCe;
using System.Data;
using Threading = System.Threading;

namespace Microsoft.Forums.OfflineStore
{
    /// <summary>
    /// Manages open connections on a per-thread basis
    /// </summary>
    public class ConnectionPool : IConnectionPool
    {
        private Dictionary<int, IDbConnection> threadConnectionMap;

        /// <summary>
        /// Gets the connection string.
        /// </summary>
        /// <value>The connection string.</value>
        public string ConnectionString
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets a connection.
        /// </summary>
        /// <returns>An open connection</returns>
        public IDbConnection Connection
        {
            get
            {
                lock (threadConnectionMap)
                {
                    int threadId = Threading.Thread.CurrentThread.ManagedThreadId;

                    IDbConnection connection = null;
                    if (threadConnectionMap.ContainsKey(threadId))
                    {
                        connection = threadConnectionMap[threadId];
                    }
                    else
                    {
                        connection = new SqlCeConnection(ConnectionString);
                        connection.Open();
                        threadConnectionMap.Add(threadId, connection);
                    }

                    return connection;
                }
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ConnectionPool"/> class.
        /// </summary>
        /// <param name="connectionString">The connection string.</param>
        public ConnectionPool(string connectionString)
        {
            threadConnectionMap = new Dictionary<int, IDbConnection>();
            ConnectionString = connectionString;
        }

    }
}
